<?php

function nospecialchars($str)
{
    if (!$str) return "";
    $str = trim($str);
    $str = preg_replace("/'/", "", $str);
    $str = preg_replace('/"/', "", $str);
    $str = preg_replace('/&/', "＆", $str);
    return $str;
}

function noNixBr($str) {
//    $str = preg_replace('//s*/', '', $str);
//    $str = str_replace(array("/r/n", "/r", "/n"), "", $str);
    $str = str_replace(PHP_EOL, "", $str);
    return $str;
}

if (!function_exists('eee')) {
    /**
     * Escape HTML entities in a string.
     *
     * @param  string $value
     * @return string
     */
    function eee($value)
    {
        return htmlentities($value, ENT_QUOTES, 'UTF-8', false);
    }
}

// 写入文件
function mywritefile($filename, $writetext, $openmod = 'w')
{
    if (@$fp = fopen($filename, $openmod)) {
        flock($fp, 2);
        fwrite($fp, $writetext);
        fclose($fp);
        return true;
    } else {
        return false;
    }
}

// 获取文件内容
function myreadfile($filename)
{
    $content = '';
    if (function_exists('file_get_contents')) {
        @$content = file_get_contents($filename);
    } else {
        if (@$fp = fopen($filename, 'r')) {
            @$content = fread($fp, filesize($filename));
            @fclose($fp);
        }
    }
    return $content;
}

//连接字符
function simplode($ids)
{
    return "'" . implode("','", $ids) . "'";
}

//处理搜索关键字
function stripsearchkey($string)
{
    $string = trim($string);
    $string = str_replace('*', '%', addcslashes($string, '%_'));
    $string = str_replace('_', '\_', $string);
    return $string;
}

//判断字符串是否存在
function strexists($haystack, $needle)
{
    return !(strpos($haystack, $needle) === FALSE);
}

function guid()
{
    if (function_exists('com_create_guid')) return substr(strtolower(com_create_guid()), 1, -1);
    mt_srand(( double )microtime() * 10000);
    $charid = md5(uniqid(rand(), true));
    $hyphen = chr(45); // "-"
    $uuid = substr($charid, 0, 8) . $hyphen . substr($charid, 8, 4) . $hyphen . substr($charid, 12, 4) . $hyphen . substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12);
    return $uuid;
}

function mkdirs($path, $mode = 0777)
{
    $dirs = explode("/", str_replace(DIRECTORY_SEPARATOR, "/", $path));
    $path = array_shift($dirs);
    for ($i = 0; $i < count($dirs); $i++) {
        $path .= DIRECTORY_SEPARATOR . $dirs[$i];
        if (!is_dir($path)) {
            mkdir($path, $mode);
        }
    }
}

function structToArray($obj)
{
    $data = array();
    $obj = (array)$obj;
    if (empty($obj)) return '';
    foreach ($obj as $key => $val) {
        if (is_object($val) || is_array($val)) {
            $data[$key] = structToArray($val);
        } else {
            $data[$key] = $val;
        }
    }
    return $data;
}


function arrayeval($array, $level = 0)
{
    $space = '';
    for ($i = 0; $i <= $level; $i++) {
        $space .= "\t";
    }
    $evaluate = "Array\n$space(\n";
    $comma = $space;
    foreach ($array as $key => $val) {
        $key = is_string($key) ? '\'' . addcslashes($key, '\'\\') . '\'' : $key;
        $val = !is_array($val) && (!preg_match("/^\-?\d+$/", $val) || strlen($val) > 12) ? '\'' . addcslashes($val, '\'\\') . '\'' : $val;
        if (is_array($val)) {
            $evaluate .= "$comma$key => " . arrayeval($val, $level + 1);
        } else {
            $evaluate .= "$comma$key => $val";
        }
        $comma = ",\n$space";
    }
    $evaluate .= "\n$space)";
    return $evaluate;
}

//去除所有空格、换行等
function mytrimtitle($str)
{
    $str = trim($str);
    $stro = array("\t", "\r\n", "\r", "\n", "&nbsp;", "'", '"', '　', ' ');
    $strr = array(' ', ' ', ' ', ' ', '', '', '', '');
    $str = str_replace($stro, $strr, $str) . " ";
    $str = str_replace(urldecode('%C2%A0'), '', $str);
    return trim($str);
}

//采取远程文件方法
function curl_get($url, $isCurl = false)
{
    if (function_exists('file_get_contents') && !$isCurl) {
        $file_contents = file_get_contents($url);
        return $file_contents;
    } else {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 50);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);
        //curl_setopt ( $ch, CURLOPT_PROXY, "proxy.tencent.com:8080");
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //是否抓取跳转后的页面
        $content = curl_exec($ch);
        if (!curl_errno($ch)) {
            $curl_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            if ($curl_code === 200) {
                return $content;
            } else {
                return false;
            }
        } else {
            curl_close($ch);
            return false;
        }
    }
}

function http_post($url, $postData)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    curl_setopt($ch, CURLINFO_HEADER_OUT, true);

    if (0 === stripos($url, 'https://')) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    }

    $output = curl_exec($ch);
    curl_close($ch);

    return $output;
}

function curl_post($url, $postData = array())
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));

    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

    if (0 === stripos($url, 'https://')) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    }

    $output = curl_exec($ch);
    // $info = curl_getinfo($ch);
    curl_close($ch);

    if ($output and $json = json_decode($output, true)) {
        return $json;
    } else {
        return false;
    }
}

function form_dropdown($name = '', $options = array(), $selected = array(), $extra = '')
{
    if (!is_array($selected)) {
        $selected = array($selected);
    }

    // If no selected state was submitted we will attempt to set it automatically
    if (count($selected) === 0) {
        // If the form name appears in the $_POST array we have a winner!
        if (isset($_POST[$name])) {
            $selected = array($_POST[$name]);
        }
    }

    if ($extra != '') $extra = ' ' . $extra;

    $multiple = (count($selected) > 1 && strpos($extra, 'multiple') === FALSE) ? ' multiple="multiple"' : '';

    $form = '<select name="' . $name . '"' . $extra . $multiple . ">\n";

    foreach ($options as $key => $val) {
        $key = (string)$key;
        $month = substr($key, 4);

        if (is_array($val) && !empty($val)) {
            $form .= '<optgroup label="' . $key . '">' . "\n";

            foreach ($val as $optgroup_key => $optgroup_val) {
                $sel = (in_array($optgroup_key, $selected)) ? ' selected="selected"' : '';

                $form .= '<option month="' . $month . '"value="' . $optgroup_key . '"' . $sel . '>' . (string)$optgroup_val . "</option>\n";
            }

            $form .= '</optgroup>' . "\n";
        } else {
            $sel = (in_array($key, $selected)) ? ' selected="selected"' : '';

            $form .= '<option month="' . $month . '"value="' . $key . '"' . $sel . '>' . (string)$val . "</option>\n";
        }
    }

    $form .= '</select>';

    return $form;
}

/**
 * 验证国内手机号
 * @param $phonestr
 * @return int
 */
function isphone($phonestr)
{
    // 手机验证
    if (!preg_match('/^1[3-9][0-9]\d{8}$/', $phonestr)) {
        return 0;
    }

    return 1;
}

/**
 * 是否是两位小数的钱
 */
function is_money($price)
{
    if (!is_numeric($price)) {
        return false;
    }

    if (!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $price)) {
        return false;
    } else {
        return true;
    }
}

/**
 * 入离语句组合
 * @param $arrivedate
 * @param $leavedate
 */
function arrive_leave_sentence($arrivedate, $leavedate)
{
    $words[] = date("m月d日入住", strtotime($arrivedate));
    $words[] = date("m月d日离店", strtotime($leavedate));
    return implode(",", $words);
}

//function orderstatus_str($orderstatus_num)
//{
//    // 订单状态文字组合
//    switch ($orderstatus_num) {
//        case C("ORDER_SUMMARY_STATUS.invalid"):
//            $orderstatus_str = "无效";
//            break;
//        case C("ORDER_SUMMARY_STATUS.notpaid"):
//            $orderstatus_str = "未支付";
//            break;
//        case C("ORDER_SUMMARY_STATUS.paid"):
//            $orderstatus_str = "已支付, 正在确认";
//            break;
//        case C("ORDER_SUMMARY_STATUS.confirmed"):
//            $orderstatus_str = "已确认";
//            break;
//        case C("ORDER_SUMMARY_STATUS.failed"):
//            $orderstatus_str = "订单失败, 等待退款";
//            break;
//        case C("ORDER_SUMMARY_STATUS.refunded"):
//            $orderstatus_str = "已退款";
//            break;
//        default:
//            $orderstatus_str = "正在处理";
//    }
//
//    return $orderstatus_str;
//}

/**
 * 是否在微信内?
 *
 * @return bool
 */
function inWeixin()
{
    $pos = stripos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger');
    if (false !== $pos) {
        return true;
    }

    return false;
}





/**
 * 是否可以使用微信支付?
 *
 * @return bool
 */
function canUseWxPay()
{
    $ua = $_SERVER['HTTP_USER_AGENT'];
    if (preg_match('/MicroMessenger\/([^\s]+)/i', $ua, $regs)) {
        if (version_compare($regs[1], '5.0', '>=')) {
            return true;
        }
    }

    return false;
}

/**
 * 一个检测环境的方法
 * production, testing, dev
 * @param $environments
 * @return int|string
 */
if (!function_exists('detectWebEnv')) {
    function detectWebEnv($environments)
    {
        if (!isset($_SERVER['SERVER_NAME'])) {
            $devMachines = array('zxc');
            $testMachines = array('AY140401162539606189Z');
            if (in_array(gethostname(), $testMachines)) {
                return 'testing';
            } else if (in_array(gethostname(), $devMachines)) {
                return 'dev';
            } else {
                return 'production';
            }
        }

        foreach ($environments as $environment => $hosts) {
            foreach ((array)$hosts as $host) {
                if (str_is($host, $_SERVER['SERVER_NAME'])) {
                    return $environment;
                }
            }
        }

        return 'production';
    }
}

/**
 * 设置缓存
 * @param string $cfgkey 缓存配置key
 * @param string $keyvaluearr  缓存key数据
 * @param null $value 缓存数据值
 * @return array|mixed|null
 */
function cache($cfgkey, $keyvaluearr, $value = '')
{
    if (!class_exists('Memcache')) {
        return false;
    }

    // 获取cache配置和cacheserver配置
    $cache_server = C('MEMCACHE_SERVER');
    $cache_config = C('CACHE_CONFIG');
    $cache_cfg = $cache_config[$cfgkey];

    // 初始化缓存
    S($cache_server);
    $cache_key = $cache_cfg['key'];
    $cache_expire = $cache_cfg['expire'];
    // 用数据格式化cachekey
    foreach ((array)$keyvaluearr as $k => $v) {
        $cache_key = str_replace('{' . $k . '}', $v, $cache_key);
    }

    if ('' === $value) { // 获取缓存
        return S($cache_key);
    } elseif (is_null($value)) { // 删除缓存
        return S($cache_key, null);
    } else { // 缓存数据
        return S($cache_key, $value, $cache_expire);
    }
}

/**
 * 匹配
 *
 * @param $pattern
 * @param $value
 * @return bool
 */
if (!function_exists('str_is')) {
    function str_is($pattern, $value)
    {
        if ($pattern == $value) return true;

        $pattern = preg_quote($pattern, '#');

        $pattern = str_replace('\*', '.*', $pattern) . '\z';

        return (bool)preg_match('#^' . $pattern . '#', $value);
    }
}


/**
 * 微信授权
 * 有session就直接走, 没session就拿base信息, TODO 没base信息就走页面授权
 *
 * @param $state
 * @param $param
 */
function new_wechat_auth($state, $param = array())
{
    $queryString = '';
    if (!empty($param)) {
        if (is_string($param)) {
            $queryString = $param;
        } else {
            $queryString = urldecode(http_build_query($param));
        }
    }

    if ($queryString) {
        // 把最终需要转发的url给带过去
        $queryString = '?passingurl=' . base64_encode($queryString);
    }

    // 组合callback地址
//    $callback = C('SITE_URL') . 'wechat/callback' . $queryString;
//    $oauth = new \Org\Wechat\Wechat(C('WECHAT_OPTIONS'));
//    $authURL = $oauth->getOauthRedirect($callback, $state, 'snsapi_base');
//    header("Location: $authURL");
}




/**
 * 将数组转换为JSON字符串（兼容中文）
 * @param $array
 * @return string
 */
function json_encode_cn($array)
{
    arrayRecursive($array, 'urlencode', true);
    $json = json_encode($array);
    return urldecode($json);
}

/**
 * 返回Json数据
 * @param $data
 * @param string $callback
 */
function jsonReturn($data, $callback = '')
{
    // 返回JSON数据格式到客户端 包含状态信息
    header('Content-Type: application/json; charset=utf-8');
    $json = json_encode($data);
    if (!empty($callback)) {
        exit("$callback($json)");
    } else {
        exit($json);
    }
}



/**
 * 百度转火星
 * @param double $bd_lat 纬度
 * @param double $bd_lon 经度
 * @return array
 */
function bd_decrypt($bd_lat, $bd_lon)
{
    $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    $x = $bd_lon - 0.0065;
    $y = $bd_lat - 0.006;
    $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
    $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
    $gg_lon = $z * cos($theta);
    $gg_lat = $z * sin($theta);

    return array(
        'lat' => $gg_lat,
        'lng' => $gg_lon,
    );
}

/**
 * GCJ-02(火星，高德) 坐标转换成 BD-09(百度) 坐标
 */
function bd_encrypt($gg_lng, $gg_lat)
{
    $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    $x = $gg_lng;
    $y = $gg_lat;
    $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
    $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
    $data['lng'] = $z * cos($theta) + 0.0065;
    $data['lat'] = $z * sin($theta) + 0.006;
    return $data;
}

/**
 * 获取语言helper
 */
function trans($pattern, $param = array(), $targetLang = '')
{
    return Translator::getTranslation($pattern, $param, $targetLang);
}

/**
 * 强制下载
 * @param string $filename
 * @param resource $data file_get_content(...)
 */
function force_download($filename = '', $data = '')
{
    if ($filename == '' OR $data == '') {
        return FALSE;
    }

    if (FALSE === strpos($filename, '.')) {
        return FALSE;
    }

//    // Grab the file extension
//    $x = explode('.', $filename);
//    $extension = end($x);
//
//    // Load the mime types
//    include(MITU_ROOT . '/include/mimes.php');
//
//    // Set a default mime if we can't find it
//    if (!isset($mimes[$extension])) {
//        $mime = 'application/octet-stream';
//    } else {
//        $mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];
//    }

    $mime = 'application/octet-stream';

    // Generate the server headers
    if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== FALSE) {
        header('Content-Type: "' . $mime . '"');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header("Content-Transfer-Encoding: binary");
        header('Pragma: public');
        header("Content-Length: " . strlen($data));
    } else {
        header('Content-Type: "' . $mime . '"');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header("Content-Transfer-Encoding: binary");
        header('Expires: 0');
        header('Pragma: no-cache');
        header("Content-Length: " . strlen($data));
    }

    exit($data);
}

/**
 * 记录日志
 * @param string $type 类型
 * @param string|array $message 内容
 */
function log_message($type, $message, $level = 'debug')
{
    $type = $type ? $type : 'default';
    if (!is_string($message)) {
        $message = serialize($message);
    }

    $log = new \Common\Model\SystemLogModel();
    $log->write(array(
        'level' => $level,
        'type' => db_escape_string($type),
        'content' => db_escape_string($message),
    ));
}

function db_escape_string($str)
{
    if (function_exists('mysql_escape_string')) {
        return mysql_escape_string($str);
    } else {
        return addslashes($str);
    }
}

/**
 * 发送邮件
 *
 * @param string $subject 主题
 * @param string $body 内容|html
 * @param $mailtoaddress
 * @param $mailtoname
 * @param bool $attach
 * @return int
 */
function sendAutoEmail($subject, $body, $mailtoaddress, $mailtoname, $attach = false)
{
    vendor('PHPMailer.PHPMailerAutoload');

    $now = date('Y-m-d H:i:s');
    $body .= "<br/><br/><br/>----<br/>this mail sent automatically @ {$now}";

    $mail = new PHPMailer(); // 实例化
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host = C('MAIL_HOST'); // smtp服务器的名称（这里以126邮箱为例）
    $mail->SMTPAuth = C('MAIL_SMTPAUTH'); // 启用smtp认证
    $mail->Username = C('MAIL_USERNAME'); // 你的邮箱名
    $mail->Password = C('MAIL_PASSWORD'); // 邮箱密码
    $mail->From = C('MAIL_FROM'); // 发件人地址（也就是你的邮箱地址）
    $mail->FromName = C('MAIL_FROMNAME'); // 发件人姓名
    $mail->WordWrap = 50; // 设置每行字符长度
    $mail->IsHTML(C('MAIL_ISHTML')); // 是否HTML格式邮件
    $mail->CharSet = C('MAIL_CHARSET'); // 设置邮件编码
    $mail->Subject = $subject; // 邮件主题
    $mail->Body = $body; // 邮件内容
    $mail->AltBody = "This is the body in plain text for non-HTML mail clients"; //邮件正文不支持HTML的备用显示

    if (empty($mailtoaddress)) {
        return 1;
    }

    if (is_array($mailtoaddress)) {
        foreach ($mailtoaddress as $addr) {
            $mail->AddAddress($addr, '');
        }
    } else {
        $mail->AddAddress($mailtoaddress, $mailtoname);;
    }

    // 添加附件
    if ($attach and file_exists($attach)) {
        $mail->AddAttachment($attach);
    }

    if (!$mail->Send()) {
        log_message('sendmail', "failed with::" . $mail->ErrorInfo . "::{$subject}");
        return 0;
    } else {
        return 1;
    }
}

if (!function_exists('merge_spaces')) {
    function merge_spaces($string)
    {
        return preg_replace('/\s(?=\s)/', "\\1", $string);
    }
}

/**
 * 发送短信
 */
if (!function_exists('sendSingleSMS')) {
    function sendSingleSMS($phone, $content, $ext = array())
    {
        if (!isphone($phone)) {
            return false;
        }

        $urlpre="http://118.145.22.178:9888/smsservice/SendSMS?UserId=1006&Password=bjmtx";
        $sendmsg = urlencode(mb_convert_encoding($content, 'GBK', 'UTF-8'));
        $phonelist = $phone;//implode(',',$sendphonearr);
        $sendurl = $urlpre."&Mobiles=".$phonelist."&Content=".$sendmsg;
        $ret=sms_curl_get($sendurl);
        $res='K';
        $status = 0;
        parse_str($ret,$resultlist);
        if($resultlist['Status']!='Succ'){
            $res.=$resultlist['Description'];
        }



        $tmpMsg = array(
            'orderid' => '0',
            'toname' => '',
            'tophone' => $phone,
            'msg' => db_escape_string($content),
            'cdate' => date('Y-m-d H:i:s'),
            'groupid' => '',
            'operatorid' => '',
            'status' => '0',
            'flag' => '0',
            'other' => $res,
            'usemsg' => '',
            'createby' => '',
        );

        $messageData = array_merge($tmpMsg, $ext);
        $SmsmtModel = new \Common\Model\SmsmtModel();
        return $id = $SmsmtModel->add($messageData);
    }

}


//采取远程文件方法
function sms_curl_get($url, $isCurl = false) {
    if (function_exists ( 'file_get_contents' ) && ! $isCurl) {
        $file_contents = file_get_contents ( $url );
        return $file_contents;
    } else {
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 30 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_NOBODY, 0 );
        //curl_setopt ( $ch, CURLOPT_PROXY, "proxy.tencent.com:8080");
        curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 0 ); //是否抓取跳转后的页面
        $content = curl_exec ( $ch );
        if (! curl_errno ( $ch )) {
            $curl_code = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
            if ($curl_code === 200) {
                return true;
            } else {
                return false;
            }
            curl_close ( $ch );
        } else {
            curl_close ( $ch );
            return false;
        }
    }
    return false;
}

function replacespecialchars($shars){
    $shars = str_replace("'","\'",$shars);
    $shars = str_replace("\n","",$shars);
    $shars = str_replace("\r","",$shars);
    return $shars;
}

function getLockname($locks,$lockid){
    $name = "";
    foreach ($locks as $ll){
        if($ll['id'] == $lockid){
            $name = $ll['lockname'];
            break;
        }
    }

    return $name;
}

function getLockprice($locks,$lockid){
    $name = "";
    foreach ($locks as $ll){
        if($ll['id'] == $lockid){
            $name = $ll['price'];
            break;
        }
    }

    return $name;
}



/**
 * excel数据导出
 * @param $phpexcel_filename    导出文件名
 * @param $phpexcel_header      excel表头
 * @param $phpexcel_data        excel数据集
 */
function excel_export($phpexcel_filename,$phpexcel_header,$phpexcel_data){

    /**
     * PHPExcel
     * 用于导出数据，只需要在需要导出数据的地方加入三个参数，并且include本脚本即可
     * $phpexcel_headerrowindex 标题行Index
     * $phpexcel_sheettitle 工作表名称
     * $phpexcel_filename   导出文件名称
     * $phpexcel_header     excel 表头数组
     * $phpexcel_data       数据二维数组，每行为一个数组单元

     *
     * $phpexcel_header = array(
    'cardno'=>array("name"=>'卡号','width'=>150),
    'cardno1'=>array("name"=>'卡号1','width'=>1501)
    );
     *
     */

    if (empty($phpexcel_data)) {
        $i = 0;
        foreach ($phpexcel_header as $key=>$value) {
            if ($i==0) {
                $phpexcel_data[$key] = '没有相关数据';
            } else {
                $phpexcel_data[$key] = '';
            }
            $i++;
        }
        $phpexcel_data = array($phpexcel_data);

    }

    if(!($phpexcel_filename && $phpexcel_header && $phpexcel_data)){
        exit('Data Error');
    }
    $cellArray = array(     1=>'A', 2=>'B', 3=>'C', 4=>'D', 5=>'E',
        6=>'F', 7=>'G', 8=>'H', 9=>'I',10=>'J',
        11=>'K',12=>'L',13=>'M',14=>'N',15=>'O',
        16=>'P',17=>'Q',18=>'R',19=>'S',20=>'T',
        21=>'U',22=>'V',23=>'W',24=>'X',25=>'Y',
        26=>'Z',
        27=>'AA', 28=>'AB', 29=>'AC', 30=>'AD', 31=>'AE',
        32=>'AF', 33=>'AG', 34=>'AH', 35=>'AI',36=>'AJ',
        37=>'AK',38=>'AL',39=>'AM',40=>'AN',41=>'AO',
        42=>'AP',43=>'AQ',44=>'AR',45=>'AS',46=>'AT',
        47=>'AU',48=>'AV',49=>'AW',50=>'AX',51=>'AY',
        52=>'AZ', 53=>'BA', 54=>'BB', 55=>'BC', 56=>'BD', 57=>'BE',
        58=>'BF', 59=>'BG', 60=>'BH', 61=>'BI', 62=>'BJ', 63=>'BK', 64=>'BL');
    $phpexcel_headerrowindex=empty($phpexcel_headerrowindex)?"1":$phpexcel_headerrowindex;
    $phpexcel_sheettitle=empty($phpexcel_sheettitle)?"list":$phpexcel_sheettitle;


    /** PHPExcel */
    // Create new PHPExcel object
    Vendor('PHPExcel.PHPExcel');
    $objPHPExcel = new \PHPExcel();
    $countheader = count($phpexcel_header);
    $headerkey = array();

    // Set properties
    $objPHPExcel->getProperties()->setCreator("yunzhanggui")
        ->setLastModifiedBy("yunzhanggui");
    $objActSheet=$objPHPExcel->getActiveSheet();

    //表头循环(标题)
    $tkey = 0;
    foreach ($phpexcel_header as $key => $tvalue){
        $tkey = $tkey+1;
        $cell  = $cellArray[$tkey].$phpexcel_headerrowindex;     //第$tkey列的第n行,列的标识符(a..z)
        $headerkey[$tkey] = $key;
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cell, $tvalue['name']);  //设置第$row列的值(标题)
        if(!empty($tvalue['width'])&&$tvalue['width']>0)
        {
            $objActSheet->getColumnDimension($cellArray[$tkey])->setWidth($tvalue['width']);
        }
    }
//print(json_encode($phpexcel_data));exit;
    /*写数据*/
    $i = $phpexcel_headerrowindex;
    foreach ($phpexcel_data as $rowdata)
    {
        $i++;
        //循环写值
        for($k =1; $k <= $countheader; $k++){
            $cell  = $cellArray[$k].$i;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cell, $rowdata[$headerkey[$k]]);  //设置第$row列的值(标题)
        }
    }

    // Rename sheet
    $objPHPExcel->getActiveSheet()->setTitle($phpexcel_sheettitle);
    // Set active sheet index to the first sheet, so Excel opens this as the first sheet
    $objPHPExcel->setActiveSheetIndex(0);

    $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);

    header("Pragma: public");

    header("Expires: 0");

    header("Cache-Control:must-revalidate, post-check=0, pre-check=0");

    header("Content-Type:application/force-download");

    header("Content-Type:application/vnd.ms-execl");

    header("Content-Type:application/octet-stream");

    header("Content-Type:application/download");

//    $import_name=iconv('utf-8','gb2312',$phpexcel_filename);
    $import_name=$phpexcel_filename;
    //这里面就是这个文件的名字,可以根据需要定义
    header('Content-Disposition:attachment;filename="'.$import_name.'.xls"');

    header("Content-Transfer-Encoding:binary");

    $objWriter->save('php://output');

}

// end